import type { UserModel } from '@/apis/model/user'
import ToastUtils from '@/utils/toast'

/**
 * 用户相关操作方法，此hook不要涉及状态
 */
export default function useUserAction(refreshFn: () => Promise<void>) {
  const router = useRouter()
  const { setMessageBox } = useMessageBox()

  /**
   * 修改用户状态，包括 api_status
   * @param user
   */
  const handleEditStatus = (user: UserModel) => {
    const title = user.status === 1 ? '禁用用户提示' : '启用用户提示'
    const content =
      user.status === 1
        ? '禁用用户会导致用户无法登录，用户账号下所有域名解析失效，请谨慎操作！'
        : '启用用户将开启用户登录权限，用户账号下所有域名解析将重新生效，请谨慎操作！'

    setMessageBox({
      content,
      title,
      async submit() {
        try {
          await putUserApi({
            id: user.id as string,
            status: user.status === 1 ? 2 : 1,
            api_status: user.api_status
          })
          refreshFn()
          ToastUtils.success('操作成功')

          setMessageBox({ visible: false })
        } finally {
          setMessageBox({ loading: false })
        }
      }
    })
  }
  const handleEditApiStatus = (user: UserModel) => {
    const title =
      user.api_status === 1 ? '禁用对外接口提示' : '启用对外接口提示'
    const content =
      user.api_status === 1
        ? '禁用后，该用户不能使用对外接口功能，请谨慎操作！'
        : '启用后，该用户可以使用对外接口功能，请谨慎操作！'

    setMessageBox({
      content,
      title,
      async submit() {
        try {
          await putUserApi({
            id: user.id as string,
            api_status: user.api_status === 1 ? 2 : 1,
            status: user.status
          })
          refreshFn()
          ToastUtils.success('操作成功')

          setMessageBox({ visible: false })
        } finally {
          setMessageBox({ loading: false })
        }
      }
    })
  }

  /**
   * 修改dns
   */
  const handleEditDnsServer = async (id: string, dns: [string, string]) => {
    await putUserDnsApi({
      id,
      ns_id_list: dns
    })
  }

  /**
   * 修改备注
   */
  const handleEditRemark = async (row: UserModel, remark: string) => {
    await putUserApi({ id: row.id as string, remark })
    refreshFn()
    ToastUtils.success('修改成功')
  }

  /**
   * 跳转用户详情
   */
  const toUserDetail = (user: UserModel) => {
    router.push({ name: 'UserDetail', params: { id: user.id } })
  }

  /**
   * 跳转用户域名
   */
  const toUserDomainView = (user: UserModel) => {
    router.push({ name: 'ManagerUserDomain', params: { id: user.id } })
  }

  return {
    handleEditStatus,
    handleEditApiStatus,
    handleEditDnsServer,
    handleEditRemark,
    toUserDetail,
    toUserDomainView
  }
}
